const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const pages = [
  'about.html',
  'contact.html',
  'feedback.html',
  'terms.html',
  'policy.html',
  'from.html'
];

module.exports = {
  entry: {
    main: './src/index.js',
    about: './src/js/pages/about.js',
    'contact': './src/js/pages/contact.js',
    feedback: './src/js/pages/feedback.js',
    terms: './src/js/pages/terms.js',
    policy: './src/js/pages/policy.js',
    from: './src/js/pages/from.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].[contenthash].js',
    clean: true,
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader']
      },
      {
        test: /\.less$/,
        use: ['style-loader', 'css-loader', 'less-loader']
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
      chunks: ['main'],
      publicPath: './'
    }),
    ...pages.map(page => new HtmlWebpackPlugin({
      template: `./src/pages/${page}`,
      filename: `pages/${page}`,
      chunks: [page.split('.')[0]],
      publicPath: '../',
      inject: 'body'
    })),
    new CopyPlugin({
      patterns: [
        {
          from: "src/images",
          to: "images"
        },
        {
          from: "src/data",
          to: "data"
        }
      ],
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash].css'
    })
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        common: {
          name: 'common',
          chunks: 'all',
          minChunks: 2,
          priority: 10,
          reuseExistingChunk: true,
          enforce: true
        },
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
          priority: 20
        },
        styles: {
          name: 'styles',
          test: /\.css$ /,
          chunks: 'all',
          enforce: true
        }
      }
    }
  },
  devServer: {
    static: './dist',
    hot: true,
    open: true,
    historyApiFallback: true
  }
}; 